//
//  PhotoBrowserViewController.swift
//  01- 搭建框架
//
//  Created by apple on 15/10/27.
//  Copyright © 2015年 任伟. All rights reserved.
//

import UIKit
import SVProgressHUD

// 注册可重用cell
private let PhotoBrowserCollectionViewCellId = "PhotoBrowserCollectionViewCellId"
class PhotoBrowserViewController: UIViewController {

    // 图像的 URL 数组
    var urls: [NSURL]
    // 选中照片的索引
    var currentIndexPath: NSIndexPath
    
    // 按钮的监听方法
    @objc private func close() {
    
        //print("关闭控制器")
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func save() {
        //print("保存照片")
        // 1. 拿到图片
        let cell = collectionView.visibleCells()[0] as! PhotoBrowserCell
        guard let image = cell.imageViwe.image else {
            return
        }
        // 2. 保存图片
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    @objc private func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject?) {
        
        let message = (error == nil) ? "保存成功" : "保存失败"
        
        SVProgressHUD.showInfoWithStatus(message)
    }
    
    /// MARK: - 构造函数
    init(urls: [NSURL], indexPath: NSIndexPath){
        self.urls = urls
        self.currentIndexPath = indexPath
        
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //print(urls)
        //print(currentIndexPath)
        // 设置选中的照片
       collectionView.scrollToItemAtIndexPath(currentIndexPath, atScrollPosition: .CenteredHorizontally, animated: false)
    }
    
    override func loadView() {
        // 1. 设置根视图
        var rect = UIScreen.mainScreen().bounds
        
        rect.size.width += 20
        
        view = UIView(frame: rect)
        // 2. 设置界面
        setupUI()
    }
    
    // 懒加载控件
    private lazy var collectionView: UICollectionView = UICollectionView(frame:CGRectZero , collectionViewLayout: PhotoBrowserViewLayout())
    private lazy var closeButton: UIButton = UIButton(title: "关闭", fontSize: 14,
        color: UIColor.whiteColor(),
        imageName: nil,
        backColor: UIColor.darkGrayColor())
    private lazy var saveButton: UIButton = UIButton(title: "保存", fontSize: 14,
        color: UIColor.whiteColor(),
        imageName: nil,
        backColor: UIColor.darkGrayColor())
    
    /// MARK: - 流水布局
    private class PhotoBrowserViewLayout: UICollectionViewFlowLayout {
        
         private override func prepareLayout() {
       
            super.prepareLayout()
            
            itemSize = collectionView!.bounds.size
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            
            scrollDirection = .Horizontal
            collectionView?.pagingEnabled = true
            collectionView?.showsHorizontalScrollIndicator = false
            collectionView?.bounces = true
        }
    }

}

/// 设置界面
extension PhotoBrowserViewController {

    // 设置界面
    private func setupUI() {
    
        // 懒加载控件
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        
        // 控件自动布局
        collectionView.frame = view.bounds
        closeButton.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.left.equalTo(view.snp_left).offset(8)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }
        saveButton.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.right.equalTo(view.snp_right).offset(-28)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }
        
        // 增加监听方法
        closeButton.addTarget(self, action: "close", forControlEvents: .TouchUpInside)
        saveButton.addTarget(self, action: "save", forControlEvents: .TouchUpInside)
        
        // 准备 collectionView
        prepareCollectionView()
    }
    
    // 准备 collectionView
    private func prepareCollectionView() {
    
        // 1. 注册可重用cell
        collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: PhotoBrowserCollectionViewCellId)
        // 2. 设置数据源
        collectionView.dataSource = self
    }
}

/// MARK: - 数据源方法
extension PhotoBrowserViewController: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoBrowserCollectionViewCellId, forIndexPath: indexPath) as! PhotoBrowserCell
        
        cell.backgroundColor = UIColor.blackColor()
        
        cell.imageURL = urls[indexPath.item]
        
        // 设置代理
        cell.photoDlegate = self
        
        return cell
    }
}

/// MARK: - PhotoBrowserCellDelegate
extension PhotoBrowserViewController: PhotoBrowserCellDelegate {
    func photoBrowserCellDidClickImage() {
        imageViewForDismiss()
        close()
    }
}

/// MARK: - 解除转场动画协议
extension PhotoBrowserViewController: PhotoBrowserDismissDelegate {

    //
    func imageViewForDismiss() -> UIImageView {
      
        let iv = UIImageView()
        
        // 设置填充模式
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        // 设置图像
        let cell = collectionView.visibleCells()[0] as! PhotoBrowserCell
        iv.image = cell.imageViwe.image
        
        // 设置位置
        iv.frame = cell.scrollView.convertRect(cell.imageViwe.frame, fromCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        
        return iv
    }
    
    //
    func indexPathForDismiss() -> NSIndexPath {
        
        return collectionView.indexPathsForVisibleItems()[0]
    }
}